/**
 *  *2010-8-14 下午02:57:04  add 
 */
package com.base.myproject.client.HR.Salary;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.base.myproject.client.Excel.DownExcelDialog;
import com.base.myproject.client.Excel.ExcelObject;
import com.base.myproject.client.Excel.Grid2ExcelBO;
import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.jdbc.DataSet;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.system.Env;
import com.base.myproject.client.ui.BaseGridPanel;
import com.base.myproject.client.ui.BaseJDBCPanel;
import com.base.myproject.client.ui.celleditor.BaseComboBoxForm;
import com.base.myproject.client.ui.dialog.ShowHtmlDialog;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.LabelField;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.layout.ColumnData;
import com.extjs.gxt.ui.client.widget.layout.ColumnLayout;
import com.extjs.gxt.ui.client.widget.toolbar.SeparatorToolItem;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;

/**
 * 内部报销
 * 
 * @author Administrator 2010-8-14 javazgw@gmail.com
 */
public class Hr_reimbursement extends BaseJDBCPanel {
	ColumnConfig systembcodecolumn;
	float time_pay;
	Button export =  new Button("导出报销单据");
	BaseComboBoxForm<BaseModelData> bsb2 = new BaseComboBoxForm<BaseModelData>(
			"bcode.bcode", "bcode.bcode %2B bcode.bname", "bcode_job,bcode",
			" where bcode.bcode=bcode_job.bcode and employstatus='在职'", true);

	public Hr_reimbursement() {
		init();
	}

	public void init() {
		initWidgetX();
		// 这里的rpc是初始化的时候载入时薪设置表里面的有效时薪值
		String sql = "select top 1 hourMoney from hr_helper_hourPay where isuse=1";
		final com.base.myproject.client.tools.GreetingServiceAsync greetingService2 = GWT
				.create(com.base.myproject.client.tools.GreetingService.class);
		greetingService2.getDataSet(sql, new AsyncCallback<DataSet>() {
			@Override
			public void onFailure(Throwable caught) {
			}

			@Override
			public void onSuccess(DataSet result) {
				if (result.getRowCount() > 0) {
					time_pay = Float
							.parseFloat(result.getValue(0, "hourMoney"));
				} else {
					time_pay = 0;
				}
				amount_set.setValue(time_pay);
			}
		});
		addbutton.addListener(Events.Select, getListener());
		addbutton.sinkEvents(Event.ONKEYPRESS);
		query.addListener(Events.Select, getListener());
		export.addListener(Events.Select, getListener());
		registerMainStore(store);
		registerStore(store);
	}
	
	public void complete() {
		super.complete();
		getToolbarll().add(new SeparatorToolItem());
		getToolbarll().add(export);
	}

	private void initWidgetX() {
		VerticalPanel vpanel = new VerticalPanel();
		vpanel.add(initInnerToolBar());
		vpanel.add(createGrid());
		vpanel.setSpacing(3);
		this.add(vpanel);
	}

	// 金额
	NumberField amount_set = new NumberField();
	// 帮工查询单号
	TextField<String> s_helper_code = new TextField<String>();
	// 帮工单号
	TextField<String> helper_code = new TextField<String>();
	// 帮工日期
	DateField helper_date = new DateField();

	Button addbutton = new Button("添加");
	Button query = new Button("查询");
	DateField datef = new DateField();

	private VerticalPanel initInnerToolBar() {

		FieldSet fs = new FieldSet();
		fs.setWidth(990);
		fs.setHeight(60);
		fs.setLayout(new ColumnLayout());
		fs.setHeading("查询操作");

		fs.add(new LabelField("报销单号:"), new ColumnData(65));
		s_helper_code.setWidth(120);
		fs.add(s_helper_code, new ColumnData(120));

		fs.add(new LabelField("查询日期:"), new ColumnData(65));
		datef.getPropertyEditor()
				.setFormat(DateTimeFormat.getFormat("yyyy-MM"));
		fs.add(datef, new ColumnData(120));

		fs.add(query, new ColumnData(120));
		fs.setBorders(true);

		FieldSet fs2 = new FieldSet();
		fs2.setWidth(990);
		fs2.setHeight(60);
		fs2.setLayout(new ColumnLayout());
		fs2.setHeading("添加操作");
		fs2.add(new LabelField("报销单号:"), new ColumnData(65));
		helper_code.setWidth(100);
		fs2.add(helper_code, new ColumnData(120));

		fs2.add(new LabelField("报销日期:"), new ColumnData(65));
		helper_date.setWidth(120);
		helper_date.getPropertyEditor().setFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		fs2.add(helper_date, new ColumnData(100));

		fs2.add(new LabelField("选择人员:"), new ColumnData(65));
		bsb2.setWidth(466);
		fs2.add(bsb2, new ColumnData(100));

		fs2.add(new LabelField("金额:"), new ColumnData(40));
		amount_set.setWidth(40);
		fs2.add(amount_set, new ColumnData(100));

		fs2.add(addbutton, new ColumnData(100));

		bsb2.addListener(Events.KeyPress, getListener());
		amount_set.addListener(Events.KeyPress, getListener());
		addbutton.addListener(Events.KeyPress, getListener());

		VerticalPanel vpanel = new VerticalPanel();
		vpanel.add(fs);
		vpanel.add(fs2);
		return vpanel;
	}

	BaseStore<BusiObject> store = null;

	BaseStore<BusiObject> getStore() {
		if (store == null) {
			createStore();
		}
		return store;
	}

	BaseStore<BusiObject> createStore() {
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		type.addField("code");
		type.getField("code").setType(String.class);
		type.addField("helper_code");
		type.getField("helper_code").setType(String.class);
		type.addField("helper_date");
		type.getField("helper_date").setType(Date.class);
		type.addField("status");
		type.getField("status").setType(String.class);
		type.addField("adddate");
		type.getField("adddate").setType(Date.class);
		type.addField("bcode");
		type.getField("bcode").setType(String.class);
		type.addField("createdate");
		type.getField("createdate").setType(Date.class);
		type.addField("createbcode");
		type.getField("createbcode").setType(String.class);
		type.addField("bankcard");
		type.getField("bankcard").setType(String.class);
		type.addField("countje");
		type.getField("countje").setType(Double.class);
		StoreInfo info = new StoreInfo();
		info.setTablename("hr_salary_reimbursement");
		info.setKeyname(new String[] { "icode" });
		info.setForcenolimit("true");
		info.setSql("select * from hr_salary_reimbursement  where datediff(month,getdate(),adddate )=0 and 1=2 order by adddate desc ");
		store = new BaseStore<BusiObject>(type, info);

		return store;
	}

	BaseGridPanel grid = null;
	NumberField C_num4 = new NumberField();// 小时数
	NumberField C_num3 = new NumberField();// 小时数

	ColumnConfig C3;
	ColumnConfig C4;
	ColumnConfig C12;
	ColumnConfig C7;
	BaseComboBoxForm<BaseModelData> bsb;

	BaseGridPanel createGrid() {
		CheckBoxSelectionModel<BusiObject> cbs = new CheckBoxSelectionModel<BusiObject>();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());

		ColumnConfig C1 = new ColumnConfig("helper_code", "报销单号", 80);
		TextField<String> hepler_code = new TextField<String>();
		C1.setEditor(new CellEditor(hepler_code));
		columns.add(C1);
		
		C7 = new ColumnConfig("bcode", "人员", 80);
		bsb = new BaseComboBoxForm<BaseModelData>("a.bcode", "a.bname", "bcode a,bcode_job b","where a.bcode = b.bcode and employstatus = '在职'", true);
		bsb.addListener(Events.Change, getListener());
		C7.setRenderer(bsb);
		C7.setEditor(bsb.getCelEditor());
		columns.add(C7);

		ColumnConfig C8 = new ColumnConfig("helper_date", "报销日期", 80);
		DateField C_data8 = new DateField();
		C_data8.getPropertyEditor().setFormat(
				DateTimeFormat.getFormat("yyyy-MM-dd"));
		C8.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		C8.setEditor(new CellEditor(C_data8));
		columns.add(C8);

		C12 = new ColumnConfig("countje", "总金额", 80);
		C12.setNumberFormat(NumberFormat.getFormat("0.00"));
		columns.add(C12);
		
		ColumnConfig C5 = new ColumnConfig("status", "状态", 80);
		C5.setHidden(true);
		columns.add(C5);

		ColumnConfig C6 = new ColumnConfig("adddate", "添加日期", 80);
		C6.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		columns.add(C6);

		ColumnConfig C10 = new ColumnConfig("bankcard", "银行帐号", 120);
		TextField<String> c10_t = new TextField<String>();
		C10.setEditor(new CellEditor(c10_t));
		columns.add(C10);

		ColumnConfig C9 = new ColumnConfig("createbcode", "创建人员", 80);
		columns.add(C9);

		ColumnModel cm = new ColumnModel(columns);
		grid = new BaseGridPanel(getStore(), cm, true, true) {
			@SuppressWarnings("unchecked")
			public void addnewrecord() {
				HashMap hp = new HashMap();
				hp.put("adddate", new Date());
				hp.put("createbcode", Env.getEnvbcode());
				grid.getBg().getStore().add(hp);
			}
		};
		cbs.setSelectionMode(SelectionMode.SINGLE);
		grid.getBg().setSelectionModel(cbs);
		grid.getBg().setWidth(990);
		grid.getBg().setHeight(300);
		return grid;
	}

	int sync = 0;
	Listener<BaseEvent> defaultlistener;
	String sqlExcel = "";

	Listener<BaseEvent> getListener() {
		if (defaultlistener != null) {
			return defaultlistener;
		}

		defaultlistener = new Listener<BaseEvent>() {
			public void handleEvent(BaseEvent be) {
				sync++;
				try {
					if (sync == 1) {
						if (be.getType() == Events.Select) {
							if (be.getSource().equals(query)) {
								if (s_helper_code.getValue() == null && datef.getValue() == null) {
									MessageBox.alert("错误", "请填写查询条件", null);
									return;
								}

								String sql = "select * from hr_salary_reimbursement where 1=1";
								String sql1 = "select helper_code,helper_date,hr_salary_reimbursement.status,adddate,bname,createdate,createbcode,bankcard,countje from hr_salary_reimbursement,bcode where bcode.bcode=hr_salary_reimbursement.bcode  ";
								String sqlEnd = " order  by adddate desc";
								if (datef.getValue() != null) {
									sql = sql + " and convert(varchar(7),helper_date,120)='"+datef.getRawValue()+"'";
									sql1 = sql1 + " and convert(varchar(7),helper_date,120)='"+datef.getRawValue()+"'";
								}

								if (s_helper_code.getValue() != null) {
									String[] code = s_helper_code.getValue().split(",");
									String searchCodes = "";
									for (String s : code) {
										searchCodes += "'" + s + "',";
									}
									searchCodes = searchCodes.substring(0, searchCodes.length() - 1);
									
									sql = sql + " and helper_code in ("+ searchCodes + ")";
									sql1 = sql1 + " and helper_code in ("+ searchCodes + ")";
								}
								sqlExcel = sql1 + sqlEnd;
								String sqlbefo = store.getStoreinfo().getSql();
								store.getStoreinfo().setSql(sql + sqlEnd);
								store.reload();
								store.getStoreinfo().setSql(sqlbefo);
							}else if(be.getSource().equals(export)){
								if (sqlExcel.equals("")) {
									MessageBox
									.alert("提示信息", "请查询数据后再进行导出，谢谢！", null);
									return;
								}
								Window.open(GWT.getHostPageBaseURL() + "hr_Jsp/exportHelper.jsp?action=0&&sql="+sqlExcel, null, null);
							}else if (be.getSource().equals(addbutton)) {
								if (helper_code.getRawValue().equals("")
										|| helper_date.getRawValue().equals("")
										|| bsb2.getRawValue().equals("") || amount_set.getRawValue().equals("0.0")) {
									MessageBox
											.alert("提示信息", "您输入的条件不完整！", null);
									return;
								}

								BusiObject bo = new BusiObject();
								bo.set("helper_code", helper_code.getValue());
								bo.set("helper_date", helper_date.getValue());
								bo.set("code", "A20");
								bo.set("countje", amount_set.getValue());
								bo.set("bcode", bsb2.getValueCode());
								bo.set("adddate", new Date());
								bo.set("createdate", new Date());
								bo.set("createbcode", Env.getEnvbcode());
								addBankCard(bo, bsb2.getValueCode());

								be.setCancelled(true);

								((ButtonEvent) be).stopEvent();
								bsb2.setValue(null);
								amount_set.setValue(0.0);
								bsb2.focus();
							}
						} else if (be.getType() == Events.Change) {
							if (be.getSource().equals(C_num3)
									|| be.getSource().equals(C_num4)) {
								if (C_num3.getValue() != null
										&& C_num4.getValue() != null) {
									double sum = (Double) C_num3.getValue()
											* (Double) C_num4.getValue();
									store.setValue("countje", sum);
								}
							} else {
								System.out.println("c7777777777777777777777777777777777");
								final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
										.create(com.base.myproject.client.tools.GreetingService.class);
								greetingService.getDataSet(
										"select hr_bankcard from bcode where bcode='"
												+ bsb.getValue().get("code")
												+ "'",
										new AsyncCallback<DataSet>() {

											@Override
											public void onFailure(Throwable caught) {

											}

											@Override
											public void onSuccess(DataSet result) {

												if (result.getRowCount() > 0) {
													store.setValue("bankcard",result.getValue(0,"hr_bankcard"));
												}
											}

										});
							}
						} else if (be.getType() == Events.RowDoubleClick) {
							if (be.getSource().equals(grid.getBg())) {
								GWT.log("RowDoubleClick");
								ShowHtmlDialog.getInstance().show(
										"asdfas<a><p>"
												+ grid.getBg().getValue(
														"amount")
												+ "</p>dd</a>", null);
							}
						}

						else if (be.getType() == Events.KeyPress) {
							if (be.getSource().equals(bsb2)) {
								if (((ComponentEvent) be).getKeyCode() == 13
										|| ((ComponentEvent) be).getKeyCode() == 10) {
									GWT.log("focus0", null);
									amount_set.focus();
								}
							} else if (be.getSource().equals(amount_set)) {
								if (((ComponentEvent) be).getKeyCode() == 13
										|| ((ComponentEvent) be).getKeyCode() == 10) {
									GWT.log("focus1", null);
									addbutton.focus();
								}
							} else if (be.getSource().equals(addbutton)) {
								if (((ComponentEvent) be).getKeyCode() == 13
										|| ((ComponentEvent) be).getKeyCode() == 10) {
									GWT.log("focus3", null);
									amount_set.focus();
								}
							}

						}
					}
				} finally {
					sync--;
				}
			}

		};
		return defaultlistener;
	}

	void addBankCard(final BusiObject bo, String bcode) {
		final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
				.create(com.base.myproject.client.tools.GreetingService.class);
		greetingService.getDataSet(
				"select hr_bankcard from bcode where bcode='" + bcode + "'",
				new AsyncCallback<DataSet>() {

					@Override
					public void onFailure(Throwable caught) {

					}

					@Override
					public void onSuccess(DataSet result) {

						if (result.getRowCount() > 0) {

							bo.set("bankcard", result
									.getValue(0, "hr_bankcard"));
						}

						getStore().add(bo);

					}

				});

	}

	/**
	 * 将数据导出到excel
	 */
	public void Export_excel() {
		ExcelObject eo = Grid2ExcelBO.getInstance().getEO(grid.getBg());
		DownExcelDialog.getInstance().javascript(eo);

	}
}
